import { connect } from 'dva';
import { Component } from 'react';
import { routerRedux } from 'dva/router';
import { Table, Pagination, Divider, Popconfirm } from 'antd';

class Users extends Component {
    constructor(props) {
        super(props);
        console.log('从 mapStateToProps 的返回值里获取到了属性并填充到了 props ');
        this.state = {
            list: props.list,
            total: props.total,
            page: props.page,
            loading: props.loading,
        };

        this.columns = [{
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        }, {
            title: 'Email',
            dataIndex: 'email',
            key: 'email',
        }, {
            title: '网站',
            dataIndex: 'website',
            key: 'website',
        }, {
            title: '操作',
            key: 'action',
            render: ( text, record ) => (
                <span>
                        <a href="">编辑</a>
                    <Divider type="vertical" />
                    <Popconfirm title="确定要删除该项吗？" onConfirm={ id => this.delHandle( record.id ) } okText="确定" cancelText="取消">
                        <a href="">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
    }

    static getDerivedStateFromProps = (nextProps, prevState) => {
        return nextProps;
    }

    pageChangeHandle = ( page, pageSize = 3 ) => {
        this.props.dispatch(routerRedux.push({
            pathname: '/users',
            query: { page },
        }));
    }

    delHandle = ( id ) => {
        this.props.dispatch({
            type: 'users/del',
            payload: id,
        })
    }

    render() {
        const { total, page, list } = this.state;
        return (
            <div>
                <Table
                    loading={ this.state.loading }
                    dataSource={ list }
                    columns={ this.columns }
                    rowKey={record => record.id}
                    pagination={false}
                />
                <Pagination
                    className="ant-table-pagination"
                    total={ total }
                    current={ page }
                    pageSize={ 3 }
                    onChange={ this.pageChangeHandle }
                />
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    console.log('激活了 Users 的 mapStateToProps');
    const { list, total, page } = state.users;
    return {
        list,
        total,
        page,
        loading: state.loading.models.users,
    }
}

export default connect(mapStateToProps)(Users);